//
// Created by leisurexi on 11/22/20.
// op_client.c
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUF_SIZE 1024

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char *argv[]) {
    int sock;
    char op_msg[BUF_SIZE];
    int op_count, result;
    struct sockaddr_in server_addr;

    if (argc != 3) {
        printf("Usage : %s <IP> <port>\n", argv[0]);
        exit(1);
    }

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1)
        error_handling("socket() error");

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);
    server_addr.sin_port = htons(atoi(argv[2]));

    if (connect(sock, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1)
        error_handling("connect() error");
    else
        puts("Connected......");

    fputs("Input operation num count: ", stdout);
    scanf("%d", &op_count);
    op_msg[0] = (char) op_count;

    for (int i = 0; i < op_count; i++) {
        fputs("Input operation num: ", stdout);
        scanf("%d", (int *) &op_msg[i * 4 + 1]);
    }
    fgetc(stdin);
    fputs("Input operator: ", stdout);
    scanf("%c", &op_msg[op_count * 4 + 1]);
    write(sock, op_msg, op_count * 4 + 2);

    read(sock, &result, sizeof(result));
    printf("Operation result: %d\n", result);

    close(sock);
    return 0;
}
